

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="js浅拷贝与深拷贝的区别和实现方式JavaScript有两种数据类型，基础数据类型和引用数据类型。基础数据类型都是按值访问的，我们可以直接操作保存在变量中的实际的值。而引用类型如Array，我们不能直接操作对象的堆内存空间。引用类型的值都是按引用访问的，即保存在变量对象中的是一个地址，该地址与堆内存的实际值相关联。 1、深拷贝和浅拷贝的区别 浅拷贝（shallow copy）：只复制指向某个对象的">
<meta property="og:type" content="article">
<meta property="og:title" content="js浅拷贝与深拷贝">
<meta property="og:url" content="http://example.com/2023/02/25/js%E6%B5%85%E6%8B%B7%E8%B4%9D%E4%B8%8E%E6%B7%B1%E6%8B%B7%E8%B4%9D/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="js浅拷贝与深拷贝的区别和实现方式JavaScript有两种数据类型，基础数据类型和引用数据类型。基础数据类型都是按值访问的，我们可以直接操作保存在变量中的实际的值。而引用类型如Array，我们不能直接操作对象的堆内存空间。引用类型的值都是按引用访问的，即保存在变量对象中的是一个地址，该地址与堆内存的实际值相关联。 1、深拷贝和浅拷贝的区别 浅拷贝（shallow copy）：只复制指向某个对象的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-24T16:38:09.000Z">
<meta property="article:modified_time" content="2023-09-05T13:21:06.260Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="axios">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>js浅拷贝与深拷贝 - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="js浅拷贝与深拷贝"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-02-25 00:38" pubdate>
          2023年2月25日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.4k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          29 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">js浅拷贝与深拷贝</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="js浅拷贝与深拷贝的区别和实现方式"><a href="#js浅拷贝与深拷贝的区别和实现方式" class="headerlink" title="js浅拷贝与深拷贝的区别和实现方式"></a>js浅拷贝与深拷贝的区别和实现方式</h2><p><strong>JavaScript有两种数据类型，基础数据类型和引用数据类型。基础数据类型都是按值访问的，我们可以直接操作保存在变量中的实际的值。而引用类型如Array，我们不能直接操作对象的堆内存空间。引用类型的值都是按引用访问的，即保存在变量对象中的是一个地址，该地址与堆内存的实际值相关联。</strong></p>
<h3 id="1、深拷贝和浅拷贝的区别"><a href="#1、深拷贝和浅拷贝的区别" class="headerlink" title="1、深拷贝和浅拷贝的区别"></a>1、深拷贝和浅拷贝的区别</h3><ul>
<li><p>浅拷贝（shallow copy）：只复制指向某个对象的指针，而不复制对象本身，新旧对象共享一块内存。</p>
</li>
<li><p>深拷贝（deep copy）：复制并创建一个一模一样的对象，不共享内存，修改新对象，旧对象保持不变。</p>
</li>
</ul>
<h3 id="2、浅拷贝的实现"><a href="#2、浅拷贝的实现" class="headerlink" title="2、浅拷贝的实现"></a>2、浅拷贝的实现</h3><p><strong>浅拷贝只是拷贝一层，更深层次对象级别的只拷贝引用(地址)，所以改变新对象，旧对象也会改变，因为新旧对象共享一块内存。</strong></p>
<p><strong>通过 Object.assign() 拷贝</strong></p>
<p><strong>Object.assign(目标文件， 原文件) 浅拷贝的方法</strong></p>
<p><strong>注意：</strong></p>
<ul>
<li>当对象只有一级属性为深拷贝；</li>
<li>当对象中有多级属性时，二级属性后就是浅拷贝；</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;script&gt;<br>    <span class="hljs-comment">// 浅拷贝只是拷贝一层, 更深层次对象级别的只拷贝引用(地址)</span><br>    <span class="hljs-keyword">var</span> obj = &#123;<br>        <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,<br>        <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;andy&#x27;</span>,<br>        <span class="hljs-attr">msg</span>: &#123;<br>            <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>        &#125;<br>    &#125;;<br>    <span class="hljs-keyword">var</span> o = &#123;&#125;;<br>    <span class="hljs-comment">// for (var k in obj) &#123;</span><br>    <span class="hljs-comment">//     // k 是属性名   obj[k] 属性值</span><br>    <span class="hljs-comment">//     o[k] = obj[k];</span><br>    <span class="hljs-comment">// &#125;</span><br>    <span class="hljs-comment">// console.log(o);</span><br>    <span class="hljs-comment">// o.msg.age = 20;</span><br>    <span class="hljs-comment">// console.log(obj);</span><br><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;--------------&#x27;</span>);<br>    <span class="hljs-comment">// Object.assign(目标文件， 原文件)  浅拷贝的方法</span><br>    <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">assign</span>(o, obj);<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(o);<br>    o.<span class="hljs-property">msg</span>.<span class="hljs-property">age</span> = <span class="hljs-number">20</span>;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj);<br>    <span class="hljs-comment">// 结果就是 o 和 obj 的 msg.age 都变成了20, 因为 o 和 obj 是共享一块内存的</span><br>&lt;/script&gt;<br><br></code></pre></td></tr></table></figure>

<h3 id="3、深拷贝的实现"><a href="#3、深拷贝的实现" class="headerlink" title="3、深拷贝的实现"></a>3、深拷贝的实现</h3><p>深拷贝的原理：复制并创建一个一模一样的对象，不共享内存，修改新对象，旧对象保持不变。</p>
<h4 id="3-1-递归遍历所有层级，实现深拷贝"><a href="#3-1-递归遍历所有层级，实现深拷贝" class="headerlink" title="3.1 递归遍历所有层级，实现深拷贝"></a>3.1 递归遍历所有层级，实现深拷贝</h4><p>我们采用<code>递归</code>的方式来封装实现深拷贝的函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 1. 使用递归的方式实现深拷贝</span><br><span class="hljs-comment">// 深拷贝拷贝多层, 每一级别的数据都会拷贝.</span><br><span class="hljs-keyword">var</span> obj = &#123;<br>    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;andy&#x27;</span>,<br>    <span class="hljs-attr">msg</span>: &#123;<br>        <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>    &#125;,<br>    <span class="hljs-attr">color</span>: [<span class="hljs-string">&#x27;pink&#x27;</span>, <span class="hljs-string">&#x27;red&#x27;</span>]<br>&#125;;<br><br><span class="hljs-keyword">var</span> o = &#123;&#125;;<br><span class="hljs-comment">// 封装函数</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">deepCopy</span>(<span class="hljs-params">newobj, oldobj</span>) &#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> k <span class="hljs-keyword">in</span> oldobj) &#123;<br>        <span class="hljs-comment">// 判断我们的属性值属于那种数据类型</span><br>        <span class="hljs-comment">// 1. 获取属性值  oldobj[k]</span><br>        <span class="hljs-keyword">var</span> item = oldobj[k];<br>        <span class="hljs-comment">// 2. 判断这个值是否是数组(首先判断数组是因为数组也属于对象)</span><br>        <span class="hljs-keyword">if</span> (item <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Array</span>) &#123;<br>            newobj[k] = [];<br>            <span class="hljs-title function_">deepCopy</span>(newobj[k], item);<br>        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Object</span>) &#123;<br>            <span class="hljs-comment">// 3. 判断这个值是否是对象</span><br>            newobj[k] = &#123;&#125;;<br>            <span class="hljs-title function_">deepCopy</span>(newobj[k], item);<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-comment">// 4. 属于简单数据类型</span><br>            newobj[k] = item;<br>        &#125;<br>    &#125;<br>&#125;;<br><span class="hljs-title function_">deepCopy</span>(o, obj);<br>o.<span class="hljs-property">msg</span>.<span class="hljs-property">age</span> = <span class="hljs-number">20</span>;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(o);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj);   <span class="hljs-comment">// obj.msg.age 还是等于 18 没有改变</span><br><span class="hljs-keyword">var</span> arr = [];<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Object</span>);  <span class="hljs-comment">// true 数组也是对象</span><br><br></code></pre></td></tr></table></figure>

<h4 id="3-2-利用-JSON-对象实现深拷贝"><a href="#3-2-利用-JSON-对象实现深拷贝" class="headerlink" title="3.2 利用 JSON 对象实现深拷贝"></a>3.2 利用 JSON 对象实现深拷贝</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 深拷贝拷贝多层, 每一级别的数据都会拷贝.</span><br><span class="hljs-keyword">var</span> obj = &#123;<br>    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;andy&#x27;</span>,<br>    <span class="hljs-attr">msg</span>: &#123;<br>        <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>    &#125;,<br>    <span class="hljs-attr">color</span>: [<span class="hljs-string">&#x27;pink&#x27;</span>, <span class="hljs-string">&#x27;red&#x27;</span>]<br>&#125;;<br><br><span class="hljs-comment">// 2. 利用 JSON 对象</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">deepCopy</span>(<span class="hljs-params">obj</span>) &#123;<br>    <span class="hljs-keyword">let</span> _obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(obj);<br>    <span class="hljs-keyword">let</span> newObj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(_obj);<br>    <span class="hljs-keyword">return</span> newObj;<br>&#125;<br><br><span class="hljs-keyword">let</span> newObj = <span class="hljs-title function_">deepCopy</span>(obj);<br>newObj.<span class="hljs-property">msg</span>.<span class="hljs-property">age</span> = <span class="hljs-number">22</span>;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newObj);  <span class="hljs-comment">//  newObj.msg.age = 22</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj);  <span class="hljs-comment">// obj.msg.age 还是等于 18 没有改变</span><br><br></code></pre></td></tr></table></figure>

<p><strong>注意： 无法实现对象中方法的深拷贝。</strong></p>
<h4 id="3-3-通过-jQuery-的-extend-方法实现深拷贝"><a href="#3-3-通过-jQuery-的-extend-方法实现深拷贝" class="headerlink" title="3.3 通过 jQuery 的 extend 方法实现深拷贝"></a>3.3 通过 jQuery 的 extend 方法实现深拷贝</h4><p>jQuery 的 extend 方法也可以拷贝对象。</p>
<p><code>$.extend([deep ], target, object1 [, objectN ])</code></p>
<ul>
<li>deep：表示是否深拷贝，true，为深拷贝；false，为浅拷贝。</li>
<li>target：Object类型 目标对象，其他对象的成员属性将被附加到该对象上。</li>
<li>object1： objectN 可选。 Object 类型 第一个以及第 N 个被合并的对象。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> a = [<span class="hljs-number">0</span>,<span class="hljs-number">1</span>,[<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],<span class="hljs-number">4</span>]<br><span class="hljs-keyword">let</span> b = $.<span class="hljs-title function_">extend</span>(<span class="hljs-literal">true</span>, [], a)<br>a[<span class="hljs-number">0</span>] = <span class="hljs-number">1</span><br>a[<span class="hljs-number">2</span>][<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>  <span class="hljs-comment">// [1,1,[1,3],4]</span><br>b  <span class="hljs-comment">// [0,1,[2,3],4]</span><br><br></code></pre></td></tr></table></figure>

<h4 id="3-4-Object-assign-，slice，concat-拷贝"><a href="#3-4-Object-assign-，slice，concat-拷贝" class="headerlink" title="3.4 Object.assign()，slice，concat 拷贝"></a>3.4 Object.assign()，slice，concat 拷贝</h4><p>当对象中只有一级属性，没有二级属性的时候，此方法为深拷贝，但是对象中有对象的时候，此方法，在二级属性以后就是浅拷贝。</p>
<ul>
<li><p>通过 <code>Object.assign()</code> 拷贝</p>
<p><code>Object.assign(目标文件， 原文件)</code> 浅拷贝的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> obj = &#123;<span class="hljs-attr">a</span>:<span class="hljs-number">1</span>,<span class="hljs-attr">b</span>:<span class="hljs-number">2</span>&#125;<br><span class="hljs-keyword">var</span> newObj = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">assign</span>(&#123;&#125;,obj)<br><br></code></pre></td></tr></table></figure></li>
<li><p>使用 <code>concat</code> 实现对数组的深拷贝</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">concat</span>(arr1, arr2,....)<br><br><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]<br><span class="hljs-keyword">var</span> newArr = [].<span class="hljs-title function_">concat</span>(arr)<br><br></code></pre></td></tr></table></figure></li>
<li><p>使用 <code>slice</code> 实现对数组的深拷贝</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">slice</span>(idx1, idx2)<br></code></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]<br><span class="hljs-keyword">var</span> newArr = arr.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>)<br><span class="hljs-comment">// slice 接受两个参数，第一个表示起始索引，第二个表示结束位置索引，省略时表示一直到末尾</span><br><br></code></pre></td></tr></table></figure>

<p>参数可以省略</p>
<ul>
<li>没有参数是拷贝数组</li>
<li>只有一个参数是从该位置起到结束拷贝数组元素</li>
<li>两个参数，拷贝从起始位置到结束位置的元素（不包含结束位置的元素：含头不含尾）</li>
</ul>
<p><strong>注意：</strong></p>
<ul>
<li>当数组中的元素均为一维是深拷贝。</li>
<li>数组中元素一维以上是值的引用。</li>
</ul>
<h4 id="3-5-lodash函数库实现深拷贝"><a href="#3-5-lodash函数库实现深拷贝" class="headerlink" title="3.5 lodash函数库实现深拷贝"></a>3.5 lodash函数库实现深拷贝</h4><p>lodash 很热门的函数库，提供了 <code>lodash.cloneDeep()</code>实现深拷贝。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js">_.<span class="hljs-title function_">cloneDeep</span>(value)<br><br>value : 要深拷贝的值。<br>返回拷贝后的值<br><br>vue 中使用 ：<br>  	 a. npm i --save lodash     下载依赖<br>  	 b. <span class="hljs-keyword">import</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;lodash&#x27;</span>  在 组件 中引入 <br>  	 c. 用法和下面的一样<br><br><span class="hljs-keyword">var</span> objects = [&#123; <span class="hljs-string">&#x27;a&#x27;</span>: <span class="hljs-number">1</span> &#125;, &#123; <span class="hljs-string">&#x27;b&#x27;</span>: <span class="hljs-number">2</span> &#125;]; <br><span class="hljs-keyword">var</span> deep = _.<span class="hljs-title function_">cloneDeep</span>(objects);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(deep[<span class="hljs-number">0</span>] === objects[<span class="hljs-number">0</span>]);<br><span class="hljs-comment">// =&gt; false</span><br><br></code></pre></td></tr></table></figure>

<h4 id="3-6-使用扩展运算符实现数组深拷贝"><a href="#3-6-使用扩展运算符实现数组深拷贝" class="headerlink" title="3.6 使用扩展运算符实现数组深拷贝"></a>3.6 使用扩展运算符实现数组深拷贝</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> a=[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]<br><span class="hljs-keyword">var</span> b=[...a];<br>b.<span class="hljs-title function_">push</span>(<span class="hljs-number">4</span>);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);<span class="hljs-comment">//1,2,3,4</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)<span class="hljs-comment">//1,2,3</span><br><br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%89%8D%E7%AB%AF/" class="category-chain-item">前端</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/axios/">#axios</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>js浅拷贝与深拷贝</div>
      <div>http://example.com/2023/02/25/js浅拷贝与深拷贝/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年2月25日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/02/25/%E5%89%8D%E7%AB%AF%E7%9F%A5%E8%AF%86%E7%82%B9/" title="前端知识点">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">前端知识点</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/02/25/axios%E4%BA%8C%E6%AC%A1%E5%B0%81%E8%A3%85/" title="axios二次封装">
                        <span class="hidden-mobile">axios二次封装</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
